import Vue from 'vue'
import router, { generateAsyncRoutes } from "@/router";
import store from "@/store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { ACCESS_TOKEN, INDEX_MAIN_PAGE_PATH } from '@/store/mutation-types'

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/mobile/login", "/mobile/questionnaire-list"/*, '/user/register', '/user/register-result'*/]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = to.meta.title;

  // _isMobile() {
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    // return flag;
  // }
  console.log('deviceModel', flag ? '手机端' : 'pc端')

  // determine whether the user has logged in
  if (Vue.ls.get(ACCESS_TOKEN)) {
    if (to.path === "/login") {
      // if is logged in, redirect to the home page
      next({ path: INDEX_MAIN_PAGE_PATH });
      NProgress.done();
    } else if (to.path === "/mobile/login") {
      // if is logged in, redirect to the home page
      next({ path: '/mobile/own-list' });
      NProgress.done();
    } else {
      console.log('router_to', to)

      console.log('store.getters.permissionList', store.getters.permissionList)
      if (store.getters.permissionList.length > 0) {
        next();
      } else {
        try {

          // get user info
          // await store.dispatch("getInfo");
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { result } = await store.dispatch('GetPermissionList')

          // if (result.menu.length === 0) {
          //   throw new Error('无菜单权限')
          // }

          let constRoutes = generateAsyncRoutes(result.menu)

          // generate accessible routes map based on roles
          store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
            // dynamically add accessible routes
            router.addRoutes(store.getters.addRouters)
            // hack method to ensure that addRoutes is complete
            // set the replace: true, so the navigation will not leave a history record
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true });
            } else {
              // 跳转到目的路由
              next({ path: redirect });
            }
          })
        } catch (error) {
          // remove token and go to login page to re-login
          console.log('router_error', error)
          store.dispatch('Logout').then(() => {
            if (flag) {
              next({ path: '/mobile/login', query: { redirect: to.fullPath } });
            } else {
              next({ path: '/login', query: { redirect: to.fullPath } });
            }
          })
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      if (flag) {
        next({ path: '/mobile/login', query: { redirect: to.fullPath } });
      } else {
        next({ path: '/login', query: { redirect: to.fullPath } })
      }
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
